package com.nti56.springboot.controller;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.nti56.springboot.model.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.nti56.springboot.service.ModuleService;
import com.nti56.springboot.service.OrganizationService;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.ParamUtil;
import com.nti56.springboot.utils.ParamUtil.Param;
import com.nti56.springboot.utils.TreeNodeUtil;


@RequestMapping("module")
@Controller
public class ModuleController extends BaseController{
      
	private static final Logger logger = LoggerFactory.getLogger(ModuleController.class);

	
	@Autowired
    private ModuleService moduleService;
	
	@Autowired
    private OrganizationService organizatioService;
	
	@RequestMapping("/toModuleList")
	@RequiresPermissions("Module:toModuleList")
    public String toModuleList(Map<String,Object> map){
		try {
			 return "system/moduleList";
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return "system/moduleList";
    }
	
	
	@RequestMapping("/toModuleAdd")
    public String toModuleAdd(HttpServletRequest request, Model model){
		String pId = (String) request.getParameter("pId");
		model.addAttribute("id", pId);
        return "system/moduleAdd";
    }
	
	
	@RequestMapping("/toModuleUpdate")
    public String toModuleUpdate(HttpServletRequest request, Model model){
		String moduleId = (String) request.getParameter("moduleId");		
		Module module = moduleService.getById(moduleId);
		model.addAttribute("moduleId", moduleId);
		model.addAttribute("module", module);
        return "system/moduleAdd";
    }
	
	
	@RequestMapping("/listModules")
    @ResponseBody
    public PageResponse listModules(HttpServletRequest request){
    	Map map = this.getParamMap(request);
        List<Module> list = moduleService.findAll(map);
		try {
			for (Module mod : list) {
				mod.setId(mod.getModuleId());
				if(StringUtil.isNotEmpty(mod.getParentId())){
					mod.set_parentId(mod.getParentId());
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
		}
		return this.getPageResponse(list);
    }
	
	private List<TreeNode> getAllResources(Map map){
		List<TreeNode> treeList = new ArrayList<TreeNode>();
		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		try {
			List<Module> list = moduleService.findAll(map);
			for (Module mod : list) {
				TreeNode tree = new TreeNode();
				tree.setId(mod.getModuleId());
				tree.setpId(mod.getParentId());
				tree.setText(mod.getModuleName());
				//tree.setChecked(org.isChecked());
				//tree.setState(org.getState());
				tree.setChildren(mod.getChildren());
				//设置树控件attributes属性的数据				
				Map<String, Object> attributes = TreeNodeUtil.getAttributes(mod);
                tree.setAttributes(attributes);				
				nodeList.add(tree);
			}
			treeList = TreeNodeUtil.getFatherNode(nodeList);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return treeList;
	}
	
	
	@RequestMapping("/getAllResources")
    @ResponseBody
    public List<TreeNode> findAll(HttpServletRequest request){
		return this.getAllResources(null);
    }
	
	@RequestMapping("/addModule")
    @ResponseBody
    public AjaxResult addModule(HttpServletRequest request,Module module){    	
    	try {
    		String moduleId = (String) request.getParameter("moduleId");
			if(moduleId == null || "".equals(moduleId)) {
				moduleService.addModule(module);
				return new AjaxResult(true,AjaxResult.SAVE_OK);
			}else {
				moduleService.updateModule(module);
				return new AjaxResult(true,AjaxResult.UPDATE_OK);
			}			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.SAVE_FAIL);
		}
    }
	
	@RequestMapping("/deleteModule")
    @ResponseBody
    public AjaxResult deleteModule(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
        	String ids = (String) map.get("ids");
    		List<String> list = Arrays.asList(ids.split(","));
    		for(String moduleId : list){
    			moduleService.deleteModule(moduleId);
    		}
			return new AjaxResult(true,AjaxResult.DLELETE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.DLELETE_FAIL);
		}
    }
	
	/**
	 * 操作角色的权限授权
	 * @param request
	 * @return
	 */
	@RequestMapping("/authSetting")
    @ResponseBody
    public AjaxResult authSetting(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
    		String entities = (String)map.get("entities");
    		String roleId = (String) request.getParameter("roleId");		
    		List<TreeNode> treeList = JSON.parseArray("["+entities+"]", TreeNode.class);
    		List<String> moduleIds = new ArrayList<String>();
    		for(TreeNode node : treeList){
    			moduleIds.add(node.getId());
    		}
    		moduleService.saveAuthSetting(roleId,moduleIds);
			return new AjaxResult(true,AjaxResult.SAVE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,AjaxResult.SAVE_FAIL);
		}
    }
	
	/**
	 * 数据角色的权限授权
	 * @param request
	 * @return
	 */
	@RequestMapping("/dataAuthSetting")
    @ResponseBody
    public AjaxResult dataAuthSetting(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
    		String entities = (String)map.get("entities");
    		String roleId = (String) request.getParameter("roleId");		
    		List<TreeNode> treeList = JSON.parseArray("["+entities+"]", TreeNode.class);
    		List<String> orgIds = new ArrayList<String>();
    		for(TreeNode node : treeList){
    			orgIds.add(node.getId());
    		}
    		moduleService.saveDataAuthSetting(roleId,orgIds);
			return new AjaxResult(true,AjaxResult.SAVE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,AjaxResult.SAVE_FAIL);
		}
    }
	
	
	@RequestMapping("/getAccordionList")
    @ResponseBody
    public List<Module> getAccordionList(HttpServletRequest request,HttpSession session){
		List<Module> accordionList = (List<Module>)session.getAttribute(Constant.SESSION_USER_AUTH_ACCORDION);
		return accordionList;
    }
	
	@RequestMapping("/getByModuleCode")
    @ResponseBody
    public Module getByModuleCode(String moduleCode){
		Module model = this.moduleService.getByModuleCode(moduleCode);
		if(model == null) {
			return new Module();
		}
		return model;
    }
	
	@RequestMapping("/getTreeList")
    @ResponseBody
	public List<TreeNode> getTreeList(HttpServletRequest request,HttpSession session){
		String pId = (String) request.getParameter("pId");
		Map map = ParamUtil.setParam("parentId", pId);
		List<Module> list = (List<Module>)session.getAttribute(Constant.SESSION_USER_AUTH_URL);
		for(Module m : list){
			//设置attributes
			Map<String, Object> attributes = TreeNodeUtil.getAttributes(m);
			m.setAttributes(attributes);	
		}
		List<TreeNode> childList = new ArrayList<TreeNode>();
		List<TreeNode> allList = Module.moduleList2TreeList(list);
		childList = TreeNodeUtil.getChilds(allList, pId);
		this.setRootStateClosed(childList, pId);
		return childList;
	}
	
	/**
	 * 把父节点设置为kong
	 * @param childList
	 * @param pId
	 */
	private void setRootStateClosed(List<TreeNode> childList,String pId){
		for(TreeNode t : childList){
			if(t.getpId().equals(pId) && !t.getChildren().isEmpty()){
				t.setState(TreeNodeUtil.STATE_CLOSED);
			}
		}
	}
	
	
	/**
	 * 授权 菜单树展示 
	 * @param request
	 * @param module
	 * @return
	 */
	@RequestMapping("/loadMenu")
    @ResponseBody
	public List<TreeNode> loadMenu(HttpServletRequest request,Module module){
		String roleId = (String) request.getParameter("roleId");
		//从数据库查询全部资源数据
		List<Module> allModuleList = moduleService.findAll(null);
		//获取当前角色的所有资源
		Param params = ParamUtil.setParam("roleId", roleId)
								.setParam("roleType", Constant.SYS_ROLE_TYPE_OPERATE);
		List<Module> checkedModuleList = moduleService.getResourceList(params);
		List<Module> list = this.getTreeNodeList(allModuleList, checkedModuleList);
		//转换数据格式
		List<TreeNode> treeList = new ArrayList<TreeNode>();
		for(Module m : list){
			TreeNode t = new TreeNode();
			t.setId(m.getModuleId());
			t.setpId(m.getParentId());
			t.setText(m.getModuleName());
			t.setChecked(m.isChecked());
			treeList.add(t);
		}
		// 转换成标准数据格式
		return TreeNodeUtil.getFatherNode(treeList);
		
	}
	
	
	/**
	 * 
	 * @param allList  数据中的全部资源
	 * @param checkedList 选中的资源
	 * @return
	 */
	private List<Module> getTreeNodeList(List<Module> allList ,List<Module> checkedList){
		List<Module> eList = new ArrayList<Module>();  
        Map<String,Module> eMap = new HashMap<String,Module>();
        for(Module m : allList){
        	eMap.put(m.getModuleId(), m);
        }
        for(Module mc : checkedList){
        	mc.setChecked(true);
        	eMap.put(mc.getModuleId(), mc);
        }
        eList.addAll(eMap.values());
        return eList;
	}
	
	
	
	/**
	 * 授权 机构树展示 
	 * @param request
	 * @param module
	 * @return
	 */
	@RequestMapping("/loadOrg")
    @ResponseBody
	public List<TreeNode> loadOrg(HttpServletRequest request,Module module){
		String roleId = (String) request.getParameter("roleId");
		//从数据库查询全部资源数据
		List<Organization> allOrgList = organizatioService.getAllOrganization(null);
		//获取当前角色的所有资源
		Param params = ParamUtil.setParam("roleId", roleId)
								.setParam("roleType", Constant.SYS_ROLE_TYPE_DATA_AUTH);
		List<Organization> checkedOrgList = moduleService.getAuthDataList(params);
		List<Organization> list = this.getTreeNodeList4DataAuth(allOrgList, checkedOrgList);
		//转换数据格式
		List<TreeNode> treeList = new ArrayList<TreeNode>();
		for(Organization m : list){
			TreeNode t = new TreeNode();
			t.setId(m.getOrgId());
			t.setpId(m.getParentId());
			t.setText(m.getDeptName());
			t.setChecked(m.isChecked());
			treeList.add(t);
		}
		// 转换成标准数据格式
		return TreeNodeUtil.getFatherNode(treeList);
	}
	
	/**
	 * 
	 * @param allList  数据中的全部资源
	 * @param checkedList 选中的资源
	 * @return
	 */
	private List<Organization> getTreeNodeList4DataAuth(List<Organization> allOrgList ,List<Organization> checkedList){
		List<Organization> eList = new ArrayList<Organization>();  
        Map<String,Organization> eMap = new HashMap<String,Organization>();
        for(Organization o : allOrgList){
        	eMap.put(o.getOrgId(), o);
        }
        for(Organization oc : checkedList){
        	oc.setChecked(true);
        	eMap.put(oc.getOrgId(), oc);
        }
        eList.addAll(eMap.values());
        return eList;
	}
}